<template>
  <div class="container px-4 max-w-7xl mx-auto">
    <!-- <p>{{ t('Check Update On GitHub') }}</p> -->
    <div class="text-9xl mb-4 flex items-center justify-center text-primary">
      <icon-local-logo v-show="!isDark" />
      <icon-local-logo-dark v-show="isDark" />
    </div>
    <Select @update:modelValue="changeLanguage">
      <SelectTrigger>
        <SelectValue :placeholder="t('Language')" class="w-12" />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value="zh-CN">中文</SelectItem>
        <SelectItem value="en-US">English</SelectItem>
        <SelectItem value="ja">日本語</SelectItem>
      </SelectContent>
    </Select>
    <div class="my-4 flex items-center justify-center gap-4">
      <Button @click="toggleDarkFn">
        <TransitionGroup name="fade">
          <icon-material-symbols:sunny-outline
            v-show="isDark"
            key="sunny"
            class="text-xl"
          />
          <icon-material-symbols:nightlight-outline
            v-show="!isDark"
            key="moon"
            class="text-xl"
          />
        </TransitionGroup>
      </Button>
      <Dialog>
        <DialogTrigger>
          <Button variant="outline" @click="openDialogFn"> 新建通知 </Button>
        </DialogTrigger>
        <DialogContent
          class="sm:max-w-[500px] grid-rows-[auto_minmax(0,1fr)_auto] max-h-[96dvh]"
          @pointer-down-outside="
            (event) => {
              // const originalEvent = event.detail.originalEvent;
              // const target = originalEvent.target as HTMLElement;
              event.preventDefault();
            }
          "
        >
          <DialogHeader>
            <DialogTitle>{{ t("Setup Notification") }}</DialogTitle>
            <DialogDescription>
              {{ t("setAsDefaultProxyDescription") }}
            </DialogDescription>
          </DialogHeader>
          <form @submit="submitFormFn" class="max-h-full flex flex-col">
            <div class="gap-4 px-2 overflow-y-auto mb-2">
              <FormField
                v-slot="{ componentField, handleBlur, handleChange, errors }"
                name="type"
              >
                <FormItem class="mb-4">
                  <FormLabel>{{ t("Notification Type") }}</FormLabel>
                  <FormControl>
                    <Select
                      class="w-full"
                      v-bind="componentField"
                      @update:modelValue="
                        (e) => {
                          changeTypeFn();
                          handleChange(e);
                        }
                      "
                      @blur="handleBlur"
                    >
                      <SelectTrigger>
                        <SelectValue :placeholder="t('Notification Type')" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectGroup>
                          <SelectItem
                            v-for="(item, value) in regularList"
                            :value="value"
                          >
                            {{ item }}
                          </SelectItem>
                          <SelectLabel class="text-[16px] opacity-35">
                            {{ t("notificationRegional") }}
                          </SelectLabel>
                          <SelectItem
                            v-for="(item, value) in regionalList"
                            :value="value"
                          >
                            {{ item }}
                          </SelectItem>
                        </SelectGroup>
                      </SelectContent>
                    </Select>
                  </FormControl>
                </FormItem>
              </FormField>
              <FormField
                v-slot="{ componentField, handleBlur, handleChange, errors }"
                name="name"
              >
                <FormItem class="mb-4">
                  <FormLabel>{{ t("Friendly Name") }}</FormLabel>
                  <FormControl>
                    <Input
                      type="text"
                      :placeholder="t('Friendly Name')"
                      v-bind="componentField"
                      @change="handleChange"
                      @blur="handleBlur"
                      :class="errors && errors.length ? '!outline-red-500' : ''"
                    />
                  </FormControl>
                  <!-- <FormDescription>{{ errors }}</FormDescription> -->
                  <FormMessage />
                </FormItem>
              </FormField>

              <component :is="currentForm" @update="updateFormFn" />
            </div>
            <DialogFooter>
              <Button type="submit">Save changes</Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";

import { ref, computed, onMounted, h } from "vue";
import { useI18n } from "vue-i18n";
import NotificationFormList from "@/components/notifications/index";
import { toast } from "@/components/ui/toast";

import { useForm } from "vee-validate";
import { toTypedSchema } from "@vee-validate/zod";
import * as z from "zod";

const { t, locale } = useI18n();

const regularList = ref({
  // "alerta": "Alerta",
  // "AlertNow": "AlertNow",
  // "apprise": t('apprise'),
  // "Bark": "Bark",
  // "clicksendsms": "ClickSend SMS",
  // "discord": "Discord",
  // "GoogleChat": "Google Chat (Google Workspace)",
  // "gorush": "Gorush",
  // "gotify": "Gotify",
  // "GrafanaOncall": "Grafana Oncall",
  // "HomeAssistant": "Home Assistant",
  // "Kook": "Kook",
  // "line": "LINE Messenger",
  // "LineNotify": "LINE Notify",
  // "lunasea": "LunaSea",
  // "matrix": "Matrix",
  // "mattermost": "Mattermost",
  // "nostr": "Nostr",
  // "ntfy": "Ntfy",
  // "octopush": "Octopush",
  // "OneBot": "OneBot",
  // "Opsgenie": "Opsgenie",
  // "PagerDuty": "PagerDuty",
  // "PagerTree": "PagerTree",
  // "pushbullet": "Pushbullet",
  // "PushByTechulus": "Push by Techulus",
  // "pushover": "Pushover",
  // "pushy": "Pushy",
  // "rocket.chat": "Rocket.Chat",
  // "signal": "Signal",
  // "slack": "Slack",
  // "squadcast": "SquadCast",
  // "SMSEagle": "SMSEagle",
  smtp: t("smtp"),
  // "stackfield": "Stackfield",
  // "teams": "Microsoft Teams",
  telegram: "Telegram",
  // "twilio": "Twilio",
  // "Splunk": "Splunk",
  webhook: "Webhook",
  // "GoAlert": "GoAlert",
  // "ZohoCliq": "ZohoCliq"
});
const regionalList = ref({
  // "AliyunSMS": "AliyunSMS (阿里云短信服务)",
  DingDing: "DingDing (钉钉自定义机器人)",
  Feishu: "Feishu (飞书) / Lark (企业)",
  // "FlashDuty": "FlashDuty (快猫星云)",
  // "FreeMobile": "FreeMobile (mobile.free.fr)",
  // "PushDeer": "PushDeer",
  // "promosms": "PromoSMS",
  // "serwersms": "SerwerSMS.pl",
  // "SMSManager": "SmsManager (smsmanager.cz)",
  // "WeCom": "WeCom (企业微信群机器人)",
  // "ServerChan": "ServerChan (Server酱)",
  // "smsc": "SMSC",
});

const formSchema = toTypedSchema(
  z.object({
    name: z.string().min(2, "letters too short").max(50),
    type: z.string(),
    webhookURL: z.string().url(),
    webhookContentType: z.string().min(2, "choose one"),
    webHookUrl: z.string().url(),
    secretKey: z.string(),
  })
);

const notification = ref({
  name: "",
  type: "",
});

const form = useForm({
  validationSchema: formSchema,
  initialValues: notification.value,
});

const changeLanguage = (value: string) => {
  locale.value = value;
};

const currentForm = computed(() => {
  if (!form.values.type) {
    return null;
  }
  return (NotificationFormList as any)[form.values.type] || null;
});

const changeTypeFn = async () => {
  const _type = form.values.type;
  await form.resetForm({
    values: {
      name: `${_type} 通知(1)`,
      type: _type,
    },
  });
  console.log('form: __ ', form.values);
};

const updateFormFn = async (value: any) => {
  const newValue = Object.assign({}, form.values, value);
  console.log("新的内容");
  console.log(newValue);
  form.setValues(newValue);
};

const isDark = ref(false);
const toggleDarkFn = () => {
  isDark.value = !isDark.value;
  document.documentElement.classList.toggle("dark");
  // 存到sessionStorage
  sessionStorage.setItem("theme", isDark.value ? "dark" : "light");
};

const openDialogFn = () => {
  form.resetForm();
};

const submitFormFn = (event: Event) => {
  event.preventDefault();
  form.handleSubmit((values) => {
    toast({
      title: "You submitted the following values:",
      description: h(
        "pre",
        { class: "mt-2 w-[340px] rounded-md bg-slate-950 p-4" },
        h("code", { class: "text-white" }, JSON.stringify(values, null, 2))
      ),
    });
  })();
};

onMounted(() => {
  if (sessionStorage.getItem("theme")) {
    if (sessionStorage.getItem("theme") === "dark") {
      isDark.value = true;
    } else {
      isDark.value = false;
    }
  } else {
    if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
      isDark.value = true;
    }
  }
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateX(-10px);
}

.fade-leave-active {
  position: absolute;
}
</style>
